package main

import (
	"context"
	"log"
	"net/http"
	"os"
	"path/filepath"

	"github.com/gin-gonic/gin"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/client-go/kubernetes"
	"k8s.io/client-go/tools/clientcmd"
)

func main() {
	// 加载 kubeconfig
	home, _ := os.UserHomeDir()
	kubeconfig := filepath.Join(home, ".kube", "config")

	config, err := clientcmd.BuildConfigFromFlags("", kubeconfig)
	if err != nil {
		log.Fatalf("无法加载 kubeconfig: %v", err)
	}

	clientset, err := kubernetes.NewForConfig(config)
	if err != nil {
		log.Fatalf("无法创建 K8s client: %v", err)
	}

	r := gin.Default()

	// 获取所有命名空间的 Pod（带状态）
	r.GET("/api/pods", func(c *gin.Context) {
		pods, err := clientset.CoreV1().Pods("").List(context.Background(), metav1.ListOptions{})
		if err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		}

		type PodInfo struct {
			Namespace string `json:"namespace"`
			Name      string `json:"name"`
			Status    string `json:"status"`
		}

		var result []PodInfo
		for _, pod := range pods.Items {
			status := "Unknown"
			if len(pod.Status.ContainerStatuses) > 0 {
				cs := pod.Status.ContainerStatuses[0]
				if cs.Ready {
					status = "Running"
				} else if cs.State.Waiting != nil {
					status = "Waiting"
				} else if cs.State.Terminated != nil {
					status = "Terminated"
				}
			}
			result = append(result, PodInfo{
				Namespace: pod.Namespace,
				Name:      pod.Name,
				Status:    status,
			})
		}

		c.JSON(http.StatusOK, result)
	})

	// 获取所有 Node（带 Ready 状态）
	r.GET("/api/nodes", func(c *gin.Context) {
		nodes, err := clientset.CoreV1().Nodes().List(context.Background(), metav1.ListOptions{})
		if err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		}

		type NodeInfo struct {
			Name   string `json:"name"`
			Status string `json:"status"`
		}

		var result []NodeInfo
		for _, node := range nodes.Items {
			status := "Unknown"
			for _, cond := range node.Status.Conditions {
				if cond.Type == "Ready" {
					if cond.Status == "True" {
						status = "Ready"
					} else {
						status = "NotReady"
					}
					break
				}
			}
			result = append(result, NodeInfo{
				Name:   node.Name,
				Status: status,
			})
		}

		c.JSON(http.StatusOK, result)
	})

	r.Run(":9090")
}
